"""
-------------------------------
- File_Name: Roles.py
- Date: 2025/2/18
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 角色接口
-------------------------------
"""

from fastapi import APIRouter, Depends, Path, Body, Query, HTTPException
from app.schemas import BaseResponse, BaseResponseExtra
from app.schemas.system.roles import *
from app.models import Role, Menu, RoleMenu, Button, RoleButton
from app.core.security import get_current_user
from app.utils.ormUtil import OrmCRUD
from app.utils.responseUtil import ResponseUtil
from app.utils.system import delete_role
from app.core.ctx import CTX_USER

router = APIRouter(prefix="/systemManage", dependencies=[Depends(get_current_user)])
tags = ["系统角色信息"]
description = "系统角色信息相关接口"


@router.post("/roles",summary="创建角色信息",response_model=BaseResponse[SystemRoleOut])
async def post_role(role_in: SystemRoleCreate):
    """系统管理-角色创建\n
    - 只新增角色信息
    - 不包括角色权限新增
    - 角色权限由“角色编辑”接口更新
    """
    # 更新创建人
    role_in.create_by = CTX_USER.get().user_name
    role_obj = await OrmCRUD(Role).add(**role_in.model_dump())
    return ResponseUtil.success_response(data=role_obj, msg=f"创建角色成功")

@router.patch("/roles/roleMenu/{id}", summary="更新角色菜单/按钮/首页权限",response_model=BaseResponse[dict])
async def _(
        _id: int|str = Path(alias="id", description="角色id"),
        role_update: SystemRoleMenuIdsUpdate = Body(...),
):
    # 菜单
    # 1. role_menu删除所有该角色数据
    await RoleMenu.filter(role_id=_id).delete()
    # 2. role_menu批量创建传入的menu_id
    add_menu_list = [RoleMenu(role_id=_id, menu_id=m) for m in role_update.menu_ids]
    await RoleMenu.bulk_create(add_menu_list)

    # 菜单按钮
    # 1. 查询button中需更新的id
    update_buttons_ids = await Button.filter(button_code__in=role_update.menu_buttons).values_list("id", flat=True)
    # 2. role_button删除所有该角色数据
    await RoleButton.filter(role_id=_id).delete()
    # 3. role_button批量创建update_buttons_ids
    add_buttons_list = [RoleButton(role_id=_id,button_id=b) for b in update_buttons_ids]
    await RoleButton.bulk_create(add_buttons_list)

    # 首页
    await Role.filter(id=_id).update(role_home=role_update.home)

    return {"code": 200,"data":{}, "msg":"更新角色菜单权限成功"}


@router.delete("/roles/{id}",summary="删除角色信息", response_model=BaseResponse[dict])
async def _(_id: int|str = Path(alias="id", description="角色id")):
    """系统管理-角色删除"""
    await delete_role(_id)
    return ResponseUtil.success_response(data={}, msg=f"删除角色成功")
#
@router.delete("/roles", summary="批量删除角色信息", response_model=BaseResponse[dict])
async def _(role_ids: str = Query(alias="ids", description="角色id")):
    ids_list = role_ids.split(",")
    for ids in ids_list:
        await delete_role(ids)
    return ResponseUtil.success_response(data={}, msg="批量删除角色成功")


@router.patch("/roles/{id}",summary="更新角色基础信息", response_model=BaseResponse[SystemRoleOut])
async def update_role(id: int|str = Path(description="角色id"),role_update: SystemRoleUpdate = Body(...)):
    """系统管理-角色更新"""
    # 更新者
    role_update.update_by = CTX_USER.get().user_name
    role_obj = await OrmCRUD(Role).update(data=role_update, id=id)
    if role_obj is None:
        raise HTTPException(status_code=404, detail=f"更新角色对象【id={id}】不存在")
    return ResponseUtil.success_response(data=role_obj,msg=f"更新角色基础信息成功")


@router.get("/getRoleList",summary="分页查询所有角色信息",response_model=BaseResponseExtra[SystemRoleOut])
@router.get("/roles",summary="分页查询所有角色信息",response_model=BaseResponseExtra[SystemRoleOut])
async def _(

        current: int = Query(default=1, ge=1,description="页码"),
        size: int = Query(default=10, ge=10,description="每页数量"),
        role_name: str = Query("", alias="roleName", description="角色名称"),
        role_code: str = Query("", alias="roleCode", description="角色编码"),
        status: str = Query("", alias="status", description="角色状态"),
):
    """系统管理-分页查询所有角色信息"""

    total, data = await OrmCRUD(Role).filter(
        current,size,order=["id"],
        role_name__icontains=role_name,
        role_code__icontains=role_code,
        status__icontains=status,
    )
    return ResponseUtil.success_response_extra( total, current, size, data,msg="查询角色成功")


@router.get("/roles/{id}",summary="查询某一角色信息",response_model=BaseResponse[SystemRoleOut])
async def get_role( id: int|str = Path(description="角色id")):
    """系统管理-查询角色信息"""
    role_obj = await OrmCRUD(Role).get_or_none(id)
    if role_obj is None:
        raise HTTPException(status_code=404, detail=f"查询角色对象【id={id}】不存在")
    return ResponseUtil.success_response(data=role_obj, msg=f"查询角色成功")


@router.get("/getAllRoles", summary="返回所有角色", response_model=BaseResponse[list[SystemAllRoleOut]])
async def _():
    """系统管理-返回所有角色"""

    # 已启用的角色
    result = await Role.filter(status='1').values("id","role_name","role_code")
    return ResponseUtil.success_response(data=result, msg="所有角色查询成功")


